import express from 'express';
import { Request, Response } from "express";
import { AppDataSource } from "../config/database";
import { success, failure } from '../utils/responses';
import { AuthRequest } from "../middlewares/user-auth";
import { BadRequest, NotFound } from "http-errors";
import { Article } from "../entities/Article";
import { Post } from "../entities/Post";
import { Share, ShareType } from "../entities/Share";
import { Repository } from "typeorm";

const router = express.Router()

/**
 * 查询当前用户是否分享
 */
router.get('/', async function (req: Request, res: Response) {
  try {
    // 获取type和targetId
    const query = req.query
    const type = Number(query.type)
    const targetId = Number(query.targetId)
    if (isNaN(targetId)) throw new BadRequest("请传入正确的id")
    if (!(type && type in ShareType)) throw new BadRequest('请传入合法的类型')

    // 在分享表中查找当前登录用户有没有为targetId分享
    const userId = (req as AuthRequest).id

    const shareRepository = AppDataSource.getRepository(Share)
    const isShare = await shareRepository.exists({
      where: {
        userId,
        type,
        targetId
      }
    })

    success(res, '成功查询分享状态', { isShare })
  } catch (error) {
    failure(res, error)
  }
});

/**
 * 分享
 */
router.post('/', async function (req: Request, res: Response) {
  try {
    // 获取type和targetId
    const { type, targetId } = req.body

    if (isNaN(targetId)) throw new BadRequest("请传入正确的id")
    if (!(type && type in ShareType)) throw new BadRequest('请传入合法的类型')

    // 检查type下有没有targetId的文章（或帖子、评论）
    let repository: Repository<Article | Post>
    let targetObject: Article | Post | null = null
    if (type === ShareType.ARTICLE) {
      repository = AppDataSource.getRepository(Article) as Repository<Article>
      targetObject = await repository.findOneBy({ id: targetId }) as Article
      if (!targetObject) throw new NotFound('没有找到文章')
    } else if (type === ShareType.POST) {
      repository = AppDataSource.getRepository(Post) as Repository<Post>
      targetObject = await repository.findOneBy({ id: targetId }) as Post
      if (!targetObject) throw new NotFound('没有找到帖子')
    }

    // 不管有没有分享，都要分享
    const userId = (req as AuthRequest).id
    const shareRepository = AppDataSource.getRepository(Share)
    const newShare = new Share()
    newShare.type = type
    newShare.userId = userId
    newShare.targetId = targetId
    await shareRepository.save(newShare)

    targetObject!.shareCount++
    await repository.save(targetObject)

    success(res, '分享成功')
  } catch (error) {
    failure(res, error)
  }
});

export default router
